from apps.merchant.shop.baseViews import *
from apps.system.user.dao import UserDao
from apps.pay.order.dao import OrderDao
from django.db.models import Sum
from django.utils import timezone
from apps.system.admin.dao import AdminDao

class ShopForCViewSet(BaseShopViewSet):
    authentication_classes = []
    permission_classes = []
    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = ShopDao().findAll().select_related('trade', 'user').filter(checkStatus='PASS', types='1')
        if params.get('scene') == '1':
            _list = _list.order_by('id')
        elif params.get('scene') == '2':
            _list = _list
        elif params.get('scene') == '3':
            _list = _list.order_by('id')
        elif params.get('scene') == '4':
            _list = _list
        return _list

    '''商家入住'''
    @action(methods=['post'], detail=False, authentication_classes = [TokenAuthentication], permission_classes = [IsAuthenticated])
    def shopCheckin(self, request):
        params = getRequestParams(request)
        _user = self.request.user
        shops = _user.user_shop.all().filter(types='1')
        if shops.count() > 0:
            if shops.count() > 1:
                return Response(response_message('您的商户异常，请联系管理员'))
            elif shops.count() == 1:
                shop = shops.first()
                if shop.checkStatus == 'PASS':
                    return Response(response_message('您已经拥有入驻的商户！'))
                elif shop.checkStatus == 'CHECKING':
                    return Response(response_message('您的商户资料正在审核中，请不要重复提交！'))
                elif shop.checkStatus == 'REFUSE':
                    params['checkStatus'] = 'CHECKING'
                    params['status'] = 0
                    ShopDao().update(shop.id, params)
                    return Response(response_success("操作成功"))

        params['status'] = 1
        params['types'] = "1" # 1:加盟店
        params['user'] = _user.id
        # 为加盟店创建一个管理员账号
        admin = AdminDao.create({
            'role': '加盟店',
            'nickname': params.get('name') + '管理员',
            'username': _user.phone,
            "password": _user.password,
        })
        print('admin', admin)
        params['admin'] = admin.id
        ShopDao().create(params)
        return Response(response_success("操作成功"))

    '''获取店铺详情'''
    @action(methods=['post'], detail=False)
    def getShopInfoForUserId(self, request):
        params = getRequestParams(request)
        _userId = params.get('userId')
        if not _userId:
            return Response(response_message('userId参数必填'))
        _user = UserDao().findOneByObjId(_userId)
        shops = ShopDao().findAll().filter(user=_user)
        if shops.count() == 0:
            return Response(response_message('该用户没有店铺'))
        model = ShopModelSerializer(shops.first()).data
        # 今日业绩
        _itemOrder = OrderDao().findAllSubOrder().filter(shop=shops.first().id).filter(Q(orderStatus='WAIT_SEND') | Q(orderStatus='READY_SEND') | Q(orderStatus='WAIT_RECEIVE') | Q(orderStatus='FINISH'))
        totalOrderMoney = _itemOrder.filter(payTime__date=timezone.now().date()).aggregate(sums=Sum('sellingPrice'))['sums'] or 0
        model['ordersForWaitSendNum'] =  str(OrderDao().findAllSubOrder().filter(shop=shops.first().id).filter(Q(orderStatus='WAIT_SEND')).count())
        model['totalOrderMoney'] = str(totalOrderMoney)
        return Response(response_success(model))